﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using EvidenceLib.Base;
using EvidenceLib.Case;
using EvidenceLib.System;
using EvidenceService.Base;
using EvidenceService.Core;
using EvidenceService.System;
using EvidenceWeb.Models;
using EvidenceWeb.Util;
using NHibernate;

namespace EvidenceWeb.Controllers
{
    public class BaseDataController : Controller
    {
        //
        // GET: /BaseData/

        #region 存放位置（仓位)

        public ActionResult StorageListView()
        {
            return View();
        }

        public ActionResult LoadStorageList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                StorageService svr = new StorageService(session);

                IList<Storage> storages = svr.LoadByHQL("from Storage");

                string json = JsonSerializerUtil.EntityToJson(storages);

                return Json(new { IsSuccess = true, Data = json });
            }
        }

        public ActionResult StorageView()
        {
            return View();
        }


        public ActionResult LoadInSEQModels()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                IDataReader reader = null;

                User user = Session["User"] as User;

                try
                {
                    int evidenceId = 0;
                    int.TryParse(Request["evidenceId"], out evidenceId);

                    int caseId = session.CreateSQLQuery("select billId from Ev_Evidence where id=" + evidenceId).UniqueResult<int>();

                    string sql = @"select s.Id,isnull(s.ParentId,0)as ParentId,s.IsLeaf,s.Name,s.FullName,
                        isnull(se3.caseid,0)as caseId,isnull(se2.evidenceid,0) as evidenceId,isnull(se2.Qty,0) as qty,s.NodeLevel 
                        from ev_storage as s 
                        left join (select sec.storageid,sec.caseid from ev_storageevidence as sec where sec.caseid=@caseId group by sec.storageid,sec.caseid) as se3 on se3.storageid=s.id 
                        left join (select * from ev_storageevidence as se where se.evidenceid=@evidenceId) as se2 on se2.storageid=s.id where s.IsUsed=1 and s.ManageDeptId = @mgrDeptId";

                    IDbCommand cmd = session.Connection.CreateCommand();

                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;

                    IDataParameter p1 = cmd.CreateParameter();
                    p1.ParameterName = "@caseId";
                    p1.DbType = DbType.Int32;
                    p1.Value = caseId;
                    cmd.Parameters.Add(p1);

                    IDataParameter p2 = cmd.CreateParameter();
                    p2.ParameterName = "@evidenceId";
                    p2.DbType = DbType.Int32;
                    p2.Value = evidenceId;
                    cmd.Parameters.Add(p2);

                    IDataParameter p3 = cmd.CreateParameter();  //只能如本部门管理的库
                    p3.ParameterName = "@mgrDeptId";
                    p3.DbType = DbType.Int32;
                    p3.Value = user.Department.Id;
                    cmd.Parameters.Add(p3);

                    reader = cmd.ExecuteReader();

                    IList<SEQModel> seqs = new List<SEQModel>();

                    while (reader.Read())
                    {
                        SEQModel seq = new SEQModel();

                        int cid = 0;
                        int eid = 0;

                        seq.StorageId = Convert.ToInt32(reader["Id"]);
                        seq.ParentId = Convert.ToInt32(reader["ParentId"]);
                        seq.NodeLevel = Convert.ToInt32(reader["NodeLevel"]);
                        seq.IsLeaf = Convert.ToBoolean(reader["IsLeaf"]);
                        seq.Name = Convert.ToString(reader["Name"]);
                        seq.FullName = Convert.ToString(reader["FullName"]);
                        seq.Qty = Convert.ToInt32(reader["Qty"]);
                        cid = Convert.ToInt32(reader["caseid"]);
                        eid = Convert.ToInt32(reader["evidenceid"]);


                        if (cid != 0 && eid != 0 && seq.Qty > 0)
                        {
                            seq.IsRecommend = true;
                            seq.Description = "优先推荐：相同物品当前存放本仓位";
                        }
                        else if (cid != 0 && eid != 0 && seq.Qty <= 0)
                        {
                            seq.IsRecommend = true;
                            seq.Description = "推荐：相同物品曾经存放本仓位";
                        }
                        else if (cid != 0 && eid == 0 && seq.Qty > 0)
                        {
                            seq.IsRecommend = true;
                            seq.Description = "推荐：相同案件当前存放本仓位";
                        }
                        else if (cid != 0 && eid == 0 && seq.Qty <= 0)
                        {
                            seq.IsRecommend = true;
                            seq.Description = "推荐：相同案件曾经存放本仓位";
                        }
                        seqs.Add(seq);
                    }

                    reader.Close();
                    reader.Dispose();

                    string json = JsonSerializerUtil.EntityToJson(seqs);
                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    if (!reader.IsClosed)
                    {
                        reader.Close();
                        reader.Dispose();
                    }

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }

        }

        public ActionResult LoadOutSEQs()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    int evidenceId = 0;
                    int.TryParse(Request["evidenceId"], out evidenceId);


                    int caseId = session.CreateSQLQuery("select billId from Ev_Evidence where id=" + evidenceId).UniqueResult<int>();

                    string sql = "select s.Id,s.ParentId,s.IsLeaf,s.Name,s.FullName,se.CaseId,se.EvidenceId,se.Qty,s.NodeLevel from ev_storage as s left join ev_storageevidence as se on s.id=se.storageid where s.IsUsed=1 and se.EvidenceId=" + evidenceId + " and se.Qty >0";

                    IList<object[]> ls = session.CreateSQLQuery(sql).List<object[]>();

                    IList<SEQModel> seqs = new List<SEQModel>();

                    foreach (object[] obj in ls)
                    {
                        SEQModel seq = new SEQModel();

                        seq.StorageId = Convert.ToInt32(obj[0]);
                        seq.ParentId = Convert.ToInt32(obj[1]);
                        seq.NodeLevel = Convert.ToInt32(obj[8]);
                        seq.IsLeaf = Convert.ToBoolean(obj[2]);
                        seq.Name = obj[3] == null ? null : obj[3].ToString();
                        seq.FullName = obj[4] == null ? null : obj[4].ToString();
                        seq.Qty = Convert.ToInt32(obj[7]);
                        seq.Description = "库存数量：" + seq.Qty;
                        seqs.Add(seq);
                    }

                    string json = JsonSerializerUtil.EntityToJson(seqs);
                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        public ActionResult LoadStorage()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                int id = 0;
                int.TryParse(Request["storageId"], out id);

                StorageService svr = new StorageService(session);

                Storage storage = svr.LoadById(id);

                string json = JsonSerializerUtil.EntityToJson(storage);

                return Json(new { IsSuccess = true, Data = json });
            }
        }


        public ActionResult SaveStorage()
        {

            using (ISession session = HbmSessionFactory.GetSession())
            {
                string json = Request["storageJson"];

                
                

                Storage storage = JsonSerializerUtil.JsonToEntity<Storage>(json);

                StorageService svr = new StorageService(session);

                if (storage.Id == 0 && storage.Parent !=null && storage.IsLeaf)
                {
                    if (svr.CheckIsUsed(storage.Parent.Id))
                    {
                        return Json(new { IsSuccess = false,Data="父节点: ["+ storage.Parent.Name +"] 已经使用，不能再添加子节点" });
                    }
                }


                svr.SaveOrUpdate(storage);

                return Json(new { IsSuccess = true ,Data = storage.Id});
            }
        }

        public ActionResult CheckStorageIsUsed()
        {
            int id = int.Parse(Request["storageId"]);
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    StorageService svr = new StorageService(session);

                    bool result=svr.CheckIsUsed(id);

                    return Json(new { IsSuccess = true, Data = result });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }

        }

        public ActionResult DeleteStorage()
        {
            int id = int.Parse(Request["storageId"]);

            using (ISession session = HbmSessionFactory.GetSession())
            {

                try
                {

                    StorageService svr = new StorageService(session);

                    

                    if (!svr.CheckIsLeaf(id))
                    {
                        return Json(new { IsSuccess = false, Data = "仓位不是子节点，不能删除！" });
                    }

                    if (svr.CheckIsUsed(id))
                    {
                        return Json(new { IsSuccess = false, Data = "仓位已经使用，不能删除！" });
                    }
                    else
                    {
                        ITransaction tx = null;
                        tx = session.BeginTransaction();
                        svr.Delete(id);
                        tx.Commit();
                        return Json(new { IsSuccess = true });
                    }
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false ,Data=ex.Message});
                }

            }

        }

        public ActionResult StorageEvidenceListView()
        {
            return View();
        }

        public ActionResult LoadStorageEvidenceList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                int totalRows = 0;

                IList<StorageEvidenceModel> ses = new List<StorageEvidenceModel>();

                try
                {
                    int pageIndex = 0;
                    int.TryParse(Request["page"], out pageIndex);

                    int pageSize = 0;
                    int.TryParse(Request["rows"], out pageSize);

                    User user = this.Session["User"] as User;

                    RoleService roleSvr = new RoleService(session);



                    bool isQuery = roleSvr.IsPermission(user.Id, "queryer");
                    string data = Request["StorageEvidenceList_Query"];

                    StorageEvidenceQuery query = JsonSerializerUtil.JsonToEntity<StorageEvidenceQuery>(data);

                    string cols = "se.id as Id,se.storageid as StorageId,s.FullName as StorageName,se.evidenceid as EvidenceId,e.Name as EvidenceName,se.CaseId as CaseId,eb.Number as CaseNo,se.Qty as Qty,ps1.Name as TranDeptName,Ps2.Name as MgrDeptName,e.OwnerName";

                    string baseSql = @" from ev_storageevidence as se 
                            inner join ev_storage as s on se.storageid=s.id 
                            inner join ev_evidence as e on se.evidenceid=e.id  
                            inner join ev_evidencebill as eb on e.billid=eb.id 
                            inner join PoliceStation as ps1 on eb.TransferDeptId =ps1.Id 
                            inner join PoliceStation as ps2 on eb.ManageDeptId =ps2.Id where se.Qty >0 ";

                    if (!string.IsNullOrEmpty(query.StorageName))
                        baseSql += " and s.Name like '%" + query.StorageName + "%'";
                    if (!string.IsNullOrEmpty(query.CaseNo))
                        baseSql += " and eb.Number like '%" + query.CaseNo + "%'";
                    if (query.QueryType ==1 )
                        baseSql += " and se.CaseId = " + query.CaseId;
                    if (!string.IsNullOrEmpty(query.EvidenceName))
                        baseSql += " and e.Name like '%" + query.EvidenceName + "%'";
                    if (!isQuery)
                        baseSql += " and (eb.TransferDeptId = " + user.Department.Id + " or eb.ManageDeptId= " + user.Department.Id + " )";

                    string totalSql = "select count(*) " + baseSql;
                    string sql = "select " + cols + baseSql + " order by s.FullPath";

                    IDbCommand cmd = session.Connection.CreateCommand();

                    totalRows = session.CreateSQLQuery(totalSql).UniqueResult<int>();

                    ISQLQuery qs = session.CreateSQLQuery(sql);

                    IList<object[]> rs = qs.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).List<object[]>();



                    foreach (object[] o in rs)
                    {
                        StorageEvidenceModel se = new StorageEvidenceModel();
                        se.Id = Convert.ToInt32(o[0]);
                        se.StorageId = Convert.ToInt32(o[1]);
                        se.StorageName = Convert.ToString(o[2]);
                        se.EvidenceId = Convert.ToInt32(o[3]);
                        se.EvidenceName = Convert.ToString(o[4]);
                        se.CaseId = Convert.ToInt32(o[5]);
                        se.CaseNo = Convert.ToString(o[6]);
                        se.Qty = Convert.ToDouble(o[7]);
                        se.TransferDeptName = Convert.ToString(o[8]);
                        se.ManageDeptName = Convert.ToString(o[9]);
                        se.OwnerName = Convert.ToString(o[10]);

                        ses.Add(se);
                    }


                    return Json(new { total = totalRows, rows = ses });
                }
                catch (Exception ex)
                {
                    return Json(new { total = totalRows, rows = ses });
                }
            }
        }

        #endregion

        #region 物品类型

        public ActionResult EvidenceTypeListView()
        {
            return View();
        }

        public ActionResult LoadEvidenceTypeList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    EvidenceTypeService svr = new EvidenceTypeService(session);

                    IList<EvidenceType> es = svr.LoadByHQL("from EvidenceType");

                    string json = JsonSerializerUtil.EntityToJson(es);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        #endregion




        #region 案件分类

        public ActionResult LoadCaseCategoryList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    CaseCategoryService svr = new CaseCategoryService(session);

                    IList<CaseCategory> ccs = svr.LoadByHQL("from CaseCategory ");

                    string json = JsonSerializerUtil.EntityToJson(ccs);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = true, Data = ex.Message });
                }
            }
        }

        #endregion


        #region 计量单位
        public ActionResult LoadUMList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    UMService svr = new UMService(session);

                    IList<UM> es = svr.LoadByHQL("from UM");

                    string json = JsonSerializerUtil.EntityToJson(es);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }
        #endregion

        #region 物品来源
        public ActionResult LoadOriginList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    OriginService svr = new OriginService(session);

                    IList<Origin> es = svr.LoadByHQL("from Origin");

                    string json = JsonSerializerUtil.EntityToJson(es);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }
        #endregion


        #region 附加说明

        public ActionResult LoadCaseFileDescriptionList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    CaseFileDescriptionService svr = new CaseFileDescriptionService(session);

                    IList<CaseFileDescription> cfds = svr.LoadByHQL("from CaseFileDescription");

                    //string json = JsonSerializerUtil.EntityToJson(es);

                    return Json(new { IsSuccess = true, rows = cfds });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        #endregion


        #region 出入库类型

        public ActionResult LoadStockTypeList()
        {
            string str = Request["billType"];

            int t = 0;

            if (!string.IsNullOrEmpty(str))
            {
                t = int.Parse(str);
            }


            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    StockTypeService svr = new StockTypeService(session);

                    string hql = null;

                    if (t > 0)
                        hql = "from StockType as s where s.BillType=" + t;
                    else
                        hql = "from StockType";

                    IList<StockType> ccs = svr.LoadByHQL(hql);

                    string json = JsonSerializerUtil.EntityToJson(ccs);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = true, Data = ex.Message });
                }
            }
        }

        #endregion
    }
}
